package com.controller;

import com.google.gson.Gson;
import com.service.UserService;
import com.service.impl.UserServiceImpl;
import com.utils.WebUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.bean.User;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

public class UserServlet extends BaseServlet {

    private UserService userService=new UserServiceImpl();

    /**
     * 判断用户编号是否存在
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void ajaxExistsUserid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String userid=req.getParameter("userid");
        boolean existsUserid=userService.existsUserid(userid);
        //封装成Map对象
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("existsUserid",existsUserid);
        Gson gson=new Gson();
        String json=gson.toJson(resultMap);
        resp.getWriter().write(json);
    }

    /**
     * 用户登录
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取请求的参数
        String userid=req.getParameter("userid");
        String password=req.getParameter("password");
        String code=req.getParameter("code");
        //获取验证码
        String token=(String)req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //删除验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        //判断验证码
        if( token!=null && token.equalsIgnoreCase(code)){
            /* if("abcde".equals(code)){*/
            //调用userService.login()登录
            User loginUser=userService.login(new User(userid,password));
            //根据Login（）方法返回结果判断登录是否成功
            if(loginUser==null){
                //返回登录页面
                req.setAttribute("mess","请重新输入用户id和密码！");
                req.getRequestDispatcher("/page/loginUser/login.jsp").forward(req,resp);
            }else{
                //登录成功
                //保存信息至session
                req.getSession().setAttribute("user",loginUser);
                resp.sendRedirect(req.getContextPath()+"/page/user/index.jsp");
            }
        }else{
            System.out.print(code+"验证码错误");
            req.setAttribute("mess",code+"验证码错误");
            req.getRequestDispatcher("/page/loginUser/login.jsp").forward(req,resp);
        }
    }

    /**
     * 用户注册
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取请求参数
        User user=WebUtils.copyParamToBean(req.getParameterMap(),new User());
        String again_password=req.getParameter("again_password");
        String code=req.getParameter("code");
        //获取验证码
        String token=(String)req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //删除验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        //验证码是否正确
        if( token!=null && token.equalsIgnoreCase(code)){
            //正确
            // 判断两次密码是否相同
            if(again_password.equals(user.getPassword())){
                //判断用户id是否可用
                if(userService.existsUserid(user.getUserid())){
                    //已存在，不可用
                    // System.out.print(userid+"已存在，不可用");
                    req.setAttribute("mess","用户名已存在！");
                    req.getRequestDispatcher("/page/loginUser/register.jsp").forward(req,resp);
                }else{
                    //调用servlet保存到数据库
                    userService.register(user);
                    req.getSession().setAttribute("user",user);
                    resp.sendRedirect(req.getContextPath()+"/page/user/index.jsp");
                }
            }else{
                System.out.print("两次输入的密码不相同");
                req.setAttribute("mess","两次输入的密码不相同！");
                req.getRequestDispatcher("/page/loginUser/register.jsp").forward(req,resp);
            }
        }else{
            //不正确
            System.out.print("验证码"+code+"不正确");
            req.setAttribute("mess","验证码"+code+"不正确");
            //转发
            req.getRequestDispatcher("/page/loginUser/register.jsp").forward(req,resp);
        }
    }

    /**
     * 修改个人基本信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void modifySelfMess(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String pet_name=req.getParameter("pet_name");
        String relname=req.getParameter("relname");
        String s=req.getParameter("sex");
        int sex=0;
        if(s=="男"){
             sex=0;
        }else{
             sex=1;
        }
        String postal_code=req.getParameter("postal_code");
        String address=req.getParameter("address");
        String telephone=req.getParameter("telephone");
        User user= (User) req.getSession().getAttribute("user");
        String userid=user.getUserid();

        System.out.println(sex);
        userService.modifyMess(userid,pet_name,relname,postal_code,telephone,address,sex);

        req.setAttribute("mess","信息修改成功！");
        System.out.println("信息修改成功！");
        user.setAddress(address);
        user.setPet_name(pet_name);
        user.setPostal_code(postal_code);
        user.setRelname(relname);
        user.setSex(sex);
        user.setTelephone(telephone);
        req.getSession().setAttribute("user",user);
        req.getRequestDispatcher("/page/user/editMess.jsp").forward(req,resp);
    }

    /**
     * 修改密码
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void modifyPass(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String password=req.getParameter("password");
        String again_password=req.getParameter("again_password");
        User user= (User) req.getSession().getAttribute("user");
        String userid=user.getUserid();

        if(again_password.equals(password)){

            userService.modifyPass(userid,password);
            req.setAttribute("mess","密码修改成功！");
            System.out.println("密码修改成功！");
            req.getRequestDispatcher("/page/user/modifyPass.jsp").forward(req,resp);
        }
        if(again_password!=password){
            req.getRequestDispatcher("/page/user/modifyPass.jsp").forward(req,resp);
        }
    }

    /**
     * 用户注消
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        User user= (User) req.getSession().getAttribute("user");
        String userid=user.getUserid();
        userService.deleteByUserid(userid);
        resp.sendRedirect(req.getContextPath()+"/index.jsp");
    }

    /**
     * 退出登录
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().invalidate();
        resp.sendRedirect(req.getContextPath());
    }


}

